const utils = require("../utils/index");

// utils/processFullUpload.js
async function processFullUpload({ filePath, fileName, uploaderName, content }) {
    let AppPackageUpload = {};
    let dot = utils.getSubstringAfterLastDot(fileName);

    if (dot === "ipa") {
        const parser = new AppInfoParser(path.join(filePath));
        let result = await parser.parse();
        AppPackageUpload.id = utils.createId();
        AppPackageUpload.create_by = uploaderName;
        AppPackageUpload.update_by = uploaderName;
        AppPackageUpload.create_date = utils.formatDate(new Date());
        AppPackageUpload.update_date = utils.formatDate(new Date());
        AppPackageUpload.version = result.CFBundleShortVersionString;
        AppPackageUpload.version_code = result.CFBundleVersion;
        AppPackageUpload.type = utils.setTypeFromPackageName(result.CFBundleName);
        let iosName = AppPackageUpload.type === 'seamobitechRemote' ? 'roku' : AppPackageUpload.type;
        AppPackageUpload.title = `${iosName}-debug-${result.CFBundleShortVersionString}(${result.CFBundleVersion})`;
        AppPackageUpload.package_name = result.CFBundleIdentifier;
        AppPackageUpload.content = content;
        AppPackageUpload.env = dot;
        // 上传逻辑
        let urlRequest = utils.getServerEndpointByType(AppPackageUpload.type, AppPackageUpload.type + '.ipa')
        let uploadResponse = await uploadFileToServer(urlRequest, filePath);
        // 入库
        const { text, values } = utils.createInsertSql("js_app_package_upload", AppPackageUpload);
        let dbresult = await utils.query(text, values);
        if (dbresult.affectedRows !== 1)
            throw new Error("数据库写入失败");
        // 回调
        debugNotice(AppPackageUpload.type, AppPackageUpload.title, AppPackageUpload.content);
        return AppPackageUpload;
    }
    else if (dot === "apk") {
        const parser = new AppInfoParser(path.join(filePath));
        let result = await parser.parse();
        AppPackageUpload.id = utils.createId();
        AppPackageUpload.create_by = uploaderName;
        AppPackageUpload.update_by = uploaderName;
        AppPackageUpload.create_date = utils.formatDate(new Date());
        AppPackageUpload.update_date = utils.formatDate(new Date());
        AppPackageUpload.package_name = result.package;
        AppPackageUpload.version = result.versionName;
        AppPackageUpload.version_code = result.versionCode;
        AppPackageUpload.type = utils.setTypeFromPackageName(result.package);
        AppPackageUpload.content = content;
        AppPackageUpload.env = dot;
        AppPackageUpload.title = `${AppPackageUpload.type}-debug-${result.versionName}(${result.versionCode})`;
        let urlRequest = utils.getServerEndpointByType(AppPackageUpload.type, AppPackageUpload.type + '.apk')
        let uploadResponse = await uploadFileToServer(urlRequest, filePath);
        // 入库
        const { text, values } = utils.createInsertSql("js_app_package_upload", AppPackageUpload);
        let dbresult = await utils.query(text, values);
        if (dbresult.affectedRows !== 1)
            throw new Error("数据库写入失败");
        debugNotice(AppPackageUpload.type, AppPackageUpload.title, AppPackageUpload.content);
        return AppPackageUpload;
    }
    else if (dot === "aab") {
        // aab用 bundletool 解析
        let stdout = await new Promise((resolve, reject) => {
            exec(`bundletool dump manifest --bundle="${filePath}"`, (err, stdout, stderr) => {
                if (err) return reject(err);
                resolve(stdout);
            })
        });
        const packageMatch = stdout.match(/package="([^"]+)"/);
        const versionCodeMatch = stdout.match(/versionCode="(\d+)"/);
        const versionNameMatch = stdout.match(/versionName="([^"]+)"/);
        const packageName = packageMatch ? packageMatch[1] : null;
        const versionCode = versionCodeMatch ? versionCodeMatch[1] : null;
        const versionName = versionNameMatch ? versionNameMatch[1] : null;

        AppPackageUpload.id = utils.createId();
        AppPackageUpload.create_by = uploaderName;
        AppPackageUpload.update_by = uploaderName;
        AppPackageUpload.create_date = utils.formatDate(new Date());
        AppPackageUpload.update_date = utils.formatDate(new Date());
        AppPackageUpload.package_name = packageName;
        AppPackageUpload.version = versionName;
        AppPackageUpload.version_code = versionCode;
        AppPackageUpload.type = utils.setTypeFromPackageName(packageName);
        AppPackageUpload.content = content;
        AppPackageUpload.env = dot;
        AppPackageUpload.title =
            `${AppPackageUpload.type}-release-${versionName}(${versionCode})`;

        let urlRequest = utils.getServerEndpointByType(AppPackageUpload.type, 'app-release.aab')
        let uploadResponse = await uploadFileToServer(urlRequest, filePath);
        // 入库
        const { text, values } = utils.createInsertSql("js_app_package_upload", AppPackageUpload);
        let dbresult = await utils.query(text, values);
        if (dbresult.affectedRows !== 1)
            throw new Error("数据库写入失败");
        // 通知
        submitFirstReviewRequest(
            utils.getGroupIdByType(AppPackageUpload.type),
            AppPackageUpload.type,
            AppPackageUpload.package_name,
            AppPackageUpload.title,
            AppPackageUpload.content
        );
        return AppPackageUpload;
    } else {
        throw new Error(`不支持的文件类型: .${dot}`);
    }
}
module.exports = processFullUpload;
